//
//  NativePickerChannel.m
//  kq_flutter_widgets
//
//  Created by wtb on 2023/4/12.
//

#import "NativePickerChannel.h"
#import "KqPhotoAlert.h"
#import "KqImageTool.h"
#import "KqTool.h"
#import <Photos/PHAsset.h>

static const NSString *IMAGE_KEY = @"IMAGE_KEY";
static const NSString *CREATE_KEY = @"CREATE_KEY";
static const NSString *MODIFIED_KEY = @"MODIFIED_KEY";

@implementation NativePickerChannel
+(void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar{
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"flutter.keqiang.com/filePicker" binaryMessenger:[registrar messenger]];
    NativePickerChannel *picker = [[NativePickerChannel alloc] init];
    [registrar addMethodCallDelegate:picker channel:channel];
}

-(void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if ([@"takePhoto" isEqualToString:call.method]){
        self.result = result;
        //拍照
        [[KqPhotoAlert sharedInstance] handleSelectCameraWithTarget:self];
    }else if ([@"pickImages" isEqualToString:call.method] || [@"pickFiles" isEqualToString:call.method]){
        self.result = result;
        //选择照片
        int count = [call.arguments[@"maxCount"] intValue];
        [[KqPhotoAlert sharedInstance] handleSelectLibraryWithTarget:self maxCount:count];
    }
}

#pragma -make UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    long interval = [KqTool getTimeInterval:[NSDate date]];
    NSDictionary *dic = [info objectForKey:UIImagePickerControllerMediaMetadata];
    if (dic) {
        NSDictionary *exifDict = [dic objectForKey:(NSString *)kCGImagePropertyExifDictionary];
        NSString *date = [exifDict objectForKey:(NSString *)kCGImagePropertyExifDateTimeOriginal];
        if (date) {
            interval = [self dateStamp:date];
        }
    }
    if (image) {
        [self getImagesInfo:@[@{IMAGE_KEY:image,CREATE_KEY:[NSNumber numberWithLong:interval],MODIFIED_KEY:[NSNumber numberWithLong:interval]}] isTakePhoto:YES];
    }
}

-(void)photoAlert:(KqPhotoAlert *__nullable)photoAlert images:(NSArray <UIImage *> *__nullable)images assets:(nonnull NSArray *)assets {
    NSMutableArray *datas = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < images.count; i++) {
        UIImage *image = images[i];
        long interval = [KqTool getTimeInterval:[NSDate date]];
        long eInterval = [KqTool getTimeInterval:[NSDate date]];
        if (assets.count > i) {
            PHAsset *pha = assets[i];
            NSDate *creationDate = pha.creationDate;
            NSDate *modificationDate = pha.modificationDate;
            if (creationDate) {
                interval = [KqTool getTimeInterval:creationDate];
            }
            if(modificationDate){
                interval = [KqTool getTimeInterval:modificationDate];
            }
        }
        [datas addObject:@{IMAGE_KEY:image,CREATE_KEY:[NSNumber numberWithLong:interval],MODIFIED_KEY:[NSNumber numberWithLong:eInterval]}];
    }
    [self getImagesInfo:datas isTakePhoto:NO];
}

-(void)getImagesInfo:(NSArray *)infos isTakePhoto:(BOOL)isTakePhoto
{
    NSMutableArray *imageList = [NSMutableArray array];
    for (int i = 0; i < infos.count; i++) {
        NSDictionary *_info = infos[i];
        UIImage *image = _info[IMAGE_KEY];
        NSData *imgData = [KqImageTool kqQualityCompressImage:image];
        if (imgData) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            NSUInteger fileSize = imgData.length;
            [dic setValue:[NSNumber numberWithInteger:fileSize] forKey:@"fileLength"];
            NSString *imgType = [KqImageTool kqImageTypeWithData:imgData];
            NSString *mime = [NSString stringWithFormat:@"image/%@",imgType];
            [dic setValue:mime forKey:@"mime"];
            [dic setValue:imgType forKey:@"suffix"];
            NSString *fileName = [NSString stringWithFormat:@"%@_%d.%@",[KqTool getNowTimeTimestamp],i,imgType];
            
            NSString *filePath = [KqTool getTmpImagePath:fileName folderName:@"kq"];
            [imgData writeToFile:filePath atomically:YES];
            [dic setValue:filePath forKey:@"filePath"];
            [dic setValue:fileName forKey:@"fileName"];
            if (_info && _info[CREATE_KEY]) {
                [dic setValue:_info[CREATE_KEY] forKey:@"createDate"];
            }
            if (_info && _info[MODIFIED_KEY]) {
                [dic setValue:_info[MODIFIED_KEY] forKey:@"modifiedDate"];
            }
            [imageList addObject:dic];
        }
    }
    if (self.result && imageList.count > 0) {
        if (isTakePhoto) {
            self.result(@{@"code":@1,@"data":imageList.firstObject});
        }else{
            self.result(@{@"code":@1,@"data":imageList});
        }
    }
}

- (long)dateStamp:(NSString *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if ([date containsString:@"-"]) {
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }else{
        [formatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];
    }
    NSDate *lastDate = [formatter dateFromString:date];
    long stamp = [lastDate timeIntervalSince1970];
    return stamp;
}

@end
